package com.sky.controller.admin;


import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RequestMapping("admin/common/")
@RestController
@Api("图片类")
public class CommonController {
    //不需要引入文件,只需要在配置文件写入就可以了
    @Value("${sky.path}")
    private String basePath;


    /**
     * file  是根据上传的名字
     *
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws IOException {
//Content-Disposition: form-data; name="file"; filename="04b223dc5aaa293fa89c3baa740ef324.jpg"
//Content-Type: image/jpeg

//        file命名是看请求的  file 的name的.
//        file是一个临时文件,放到临时文件夹中.请求完成后会删除.用断点才可以看见.
//        所以我们要把他存到指定位置,离开临时文件夹

        log.info(String.valueOf(file));

//      原始的文件名字
        String originalFilename = file.getOriginalFilename();

        int i = originalFilename.lastIndexOf(".");
//        substring（子字符串）操作通常使用左闭右开的方式。
//        后缀
        String suffix = originalFilename.substring(i, originalFilename.length());
//        文件名字没有后缀
        String filename = UUID.randomUUID().toString();

        String new_filename = filename + suffix;
        File dir = new File(basePath);
        if (!dir.exists()) {
//            目录不存在,则多级创建
            dir.mkdirs();
        }


//        让临时文件转到指定位置
        file.transferTo(new File(basePath + new_filename));

//        照片名字存到数据库中.
        return Result.success(new_filename);
    }

    /**
     * 文件下载
     *
     * @param name
     * @param httpServletResponse
     */

    @GetMapping("download")
    @ApiOperation("文件下载")
    public void download(@RequestParam("name") String name, HttpServletResponse httpServletResponse) throws IOException {
//        输入流,通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(basePath + name);
//        输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        httpServletResponse.setContentType("image/jpeg");
        int len;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }
}
